package day20240922;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/day20240922/Delete")
public class Delete extends HttpServlet {
    public Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        System.out.println("JDBC驱动加载成功！");
        String url = "jdbc:mysql://localhost:3306/manageman";
        String user = "root";
        String password = "lcw0909.";
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String parameter = req.getParameter("userid-0");
        Integer i = Integer.valueOf(parameter);
        try {
            Connection connection = getConnection();
            String sql = "DELETE FROM mm WHERE id IN (" + i + ")";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            int rowsInserted = preparedStatement.executeUpdate();
            if (rowsInserted > 0) {
                System.out.println("数据删除成功！");
            }
            resp.getWriter().write("<!DOCTYPE html>\n" +
                    "<html lang=\"en\">\n" +
                    "<head>\n" +
                    "    <meta charset=\"UTF-8\">\n" +
                    "    <title>管理页面</title>\n" +
                    "</head>\n" +
                    "<body>\n" +
                    "<a href=\"manage_jsp.jsp\" style = \"font-size = \"100px\"\">删除完成点击返回管理界面</a>" +
                    "</body>\n" +
                    "</html>");
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
